import { reqLogin, reqLogout } from "../../api/user";

//当组件读取vuex的数据的时候就会先读取localStorage、sessionStorage
const state = JSON.parse(localStorage.getItem("user")) ||
JSON.parse(sessionStorage.getItem("user")) || {
	name: "",
	nickName: "",
	token: ""
};

const getters = {};

const actions = {
	async login({ commit }, data) {
		const response = await reqLogin(data);
		commit("LOGIN", response);
		//这里return出去的值，外面调用这个方法的返回值就是这个值
		return response;
	},
	async logout({ commit }) {
		//发请求给服务器退出登录
		await reqLogout();
		commit("LOGOUT");
	}
};

const mutations = {
	LOGIN(state, data) {
		state.name = data.name;
		state.nickName = data.nickName;
		state.token = data.token;
	},
	LOGOUT(state) {
		state.name = "";
		state.nickName = "";
		state.token = "";
	}
};

export default {
	namespaced: true,
	state,
	getters,
	actions,
	mutations
};
